/*********************************************************************************
 *      Copyright:  (C) 2020 makun<1394987689@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  mosquitto_pub.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2020年07月08日)
 *         Author:  makun <1394987689@qq.com>
 *      ChangeLog:  1, Release initial version on "2020年07月08日 22时30分04秒"
 *                 
 ********************************************************************************/

#include "mosquitto_pub.h"
#define  PROG_VERSION "1.0.0"
#define  PATH_INT "/home/pi/mqtt/aliyun_mosquitto/aliyun_mosquitto_pub/etc/mqtt_aly_conf.ini"


void pub_conn_callback(struct mosquitto *mosq, void *obj, int rc);
static void  print_usage( char *progname)
{
    printf("Usage  %s [option]...\n", progname);
    printf("%s is makun studi MQTT daemon program running on RaspberryPi\n", progname);
    printf("-h (--help): Display this help information\n");
    printf("-v (--version): Display the program version\n");

    printf("%s  Version %s\n", progname, PROG_VERSION);
    return ;
}

int main (int argc, char **argv)
{
    char         *host = NULL;
    int          port ;
    char         *clientid = NULL;
    char         *user = NULL;
    char         *passwd = NULL;
    char         *topic = NULL;
    int          rv = -1;
    int          opt= -1;
    char         *progname = NULL;
    bool         session = true;
    mqtt_ctx_t   mqtt;

    struct mosquitto *mosq = NULL;

    
    struct option long_options[]= {
        {"help", no_argument, NULL, 'h'},
        {"version", no_argument, NULL, 'v'},
        {0, 0, 0, 0}
    };

    progname = (char *)basename(argv[0]);

    while( (opt = getopt_long(argc, argv,"hv", long_options,NULL)) != -1)
    {
        switch (opt)
        {
            case 'v':
                printf("%s Version %s\n",progname, PROG_VERSION);
                return 0;
            case 'h':
                print_usage(progname);
                return 0;
            default:
                break;
        }
    }

    /*
    rv=set_mqtt_conf(PATH_INT, host, port, clientid, user,passwd, topic);

    if(rv < 0)
    {
        printf("set mqtt conf is failure %d\n", rv);
        return -1;
    }*/

    log_open();
    memset(&mqtt, 0, sizeof(mqtt));

    rv = gain_mqtt_conf(PATH_INT, &mqtt);
    if(rv < 0)
    {
        log_error("gain mqtt conf failure %d\n", rv);
    }
    


    /*必须在任何其他mosquitto功能之前调用*/
    mosquitto_lib_init();

    /*创建一个新的mosquitto客户端实例,第二个参数为true，代理清除断开连接时的所有消息和订阅*/
    mosq = mosquitto_new(mqtt.clientid,session, (void *)&mqtt );
    if(!mosq)
    {
        log_error("mosquitto new failure: %s\n", strerror(errno));
        goto cleanup;
    }

    log_info("Create mosquitto successfuly\n");

    /*设置连接回调，当代理发送CONNACK消息以响应连接时，将调用此方法*/
    mosquitto_connect_callback_set(mosq, pub_conn_callback);


    /*配置mosquitto实例的用户名和密码*/
    if( mosquitto_username_pw_set(mosq, mqtt.username,mqtt.passwd) !=MOSQ_ERR_SUCCESS)
    {
        log_error("mosquitto username and passwd failure:%s\n",strerror(errno));
        goto cleanup;
    }

    while(1)
    {
        /*连接MQTT代理*/
        if(mosquitto_connect(mosq, mqtt.hostname, mqtt.port, mqtt.keepalive) != MOSQ_ERR_SUCCESS )
        {
            log_error("mosquitto connect server failure:%s\n",strerror(errno));
            continue;
            sleep(1);
        }

        /*无线阻塞循环调用loop*/
        mosquitto_loop_forever(mosq, -1, 1 );
        sleep(10);
    }
    //log_close();

cleanup:
    log_error("program will exit\n");
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    return 0;

}


void pub_conn_callback(struct mosquitto *mosq, void *obj, int rc)
{
    mqtt_ctx_t  *mqtt;
    int mid;
    char    *msg;
    cJSON   *root = cJSON_CreateObject();
    cJSON   *item = cJSON_CreateObject();
    int     retain = 0;
    float   temp;
    float   humidity;
    int     rv = -1;
    float    payload1;
    float    payload2;
    if(!mosq ||!obj)
    {
        log_error("invalid input argument\n");
        return ;
    }
    
    rv = get_temp_humidity( &temp, &humidity);
    if(rv == 0)
    {
        payload1 = temp;
        payload2 = humidity;
        
    }
    mqtt = (mqtt_ctx_t *)obj;

    cJSON_AddItemToObject(root, "method", cJSON_CreateString(mqtt->method));//根节点下添加
    cJSON_AddItemToObject(root, "id", cJSON_CreateString(mqtt->id));//根节点下添加
    cJSON_AddItemToObject(root, "params",item);
    cJSON_AddItemToObject(item, "CurrentHumidity", cJSON_CreateNumber(payload2));
    cJSON_AddItemToObject(item, "CurrentTemperature", cJSON_CreateNumber(payload1));
    cJSON_AddItemToObject(root, "version", cJSON_CreateString(mqtt->version));
    
    msg = cJSON_Print(root);
    log_info("%s\n", msg);

    if(!rc)
    {  
        if( mosquitto_publish(mosq,&mid,mqtt->pubTopic,strlen(msg)+1, msg, mqtt->pubQos, retain) != MOSQ_ERR_SUCCESS )  
        {   
            log_error("Mosq_Publish() error: %s\n", strerror(errno));
            return ;
        }
        log_info("pubilush topic:%s\n",mqtt->pubTopic) ;
    }
    mosquitto_disconnect(mosq) ;

}






